package com.cedifie.lendapp.dv_data

import android.content.Context
import com.cedifie.lendapp.dv_data.dv.CedDvBty
import com.cedifie.lendapp.dv_data.dv.CedDvContract
import com.cedifie.lendapp.dv_data.dv.CedDvMsage
import com.google.gson.Gson

class CedDvMode(val context: Context, val product: String, val token: String) {

    private fun formatReportType1(path: String, fetchData: () -> String?): String? {
        if (!formatReportType3(path)) return null
        val content = fetchData()?:""

        // TODO: 加密操作
//        val encrypted: String = ASAesUtil.encryptDefault(content)
//        return encrypted
        return content
    }

    private fun formatReportType2(path: String, key: String, fetchData: () -> String?): String? {
        if (!formatReportType3(path)) return null
        val data = fetchData() ?: return null
        val params = formatReportType4(path).apply { put(key, data) }
        val content = Gson().toJson(params).trim()

        // TODO: 加密操作
//        val encrypted: String = ASAesUtil.encryptDefault(content)
//        return encrypted
        return content
    }

    private fun formatReportType3(path: String) = listOf(product, token, path).all { it.isNotBlank() }

    private fun formatReportType4(path: String) = hashMapOf<String, Any>(
        "path" to path.replace("/", ""),
        "token" to token,
        "product" to product
    )

    fun reportCedDvDevice(path: String) = formatReportType1(path) {
        CedDvContract.queryCedDvDevice(context, product, token, path)
    }

    fun reportCedDvMsage(path: String) = formatReportType1(path) {
        CedDvMsage(context, product, token, path).queryCedDvMsage()
    }

    fun reportCedDvHdw(path: String) = formatReportType2(path, "deviceHardwareGzip") {
        CedDvContract.queryCedDvHdw(context)
    }

    fun reportCedDvBty(path: String, onResult: (String?) -> Unit) {
        CedDvBty(context = context, onResult = { bd ->
            val result = formatReportType2(path, "deviceBatteryGzip") { bd }
            onResult.invoke(result)
        }).start()
    }

    fun reportCedDvWf(path: String) = formatReportType2(path, "deviceWifiGzip") {
        CedDvContract.queryCedDvWf(context)
    }

    fun reportCedDvStag(path: String) = formatReportType2(path, "deviceStorageGzip") {
        CedDvContract.queryCedDvStag(context)
    }

    fun reportCedDvApp(path: String) = formatReportType2(path, "appListGzip") {
        CedDvContract.queryCedDvApp(context)
    }
}